import { computed, reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useStorage, StorageSerializers } from '@vueuse/core'
import { Message } from '@/components'
import { FormIndex } from "@types"
import md5 from 'md5'
import { goLogin } from '@/request'

const userInfo = useStorage("userInfo", null, undefined, {
    serializer: StorageSerializers.object
})
const token = ref(useStorage("token", "", undefined))

export const useUser = () => {
    const router = useRouter()
    const isRemember=!!userInfo.value
    
    const loginForm = reactive<FormIndex>({
        username: userInfo.value? userInfo.value.username :"",
        password:userInfo.value? userInfo.value.password :"",
        remember: isRemember?userInfo.value.remember:false,
    })


    const login = async () => {
        if(loginForm.username===''){
            return Message.error('用户名不能为空')
        }
        if(loginForm.password===''){
            return Message.error('密码不能为空')
        }
        goLogin({
            username:loginForm.username, 
            password:md5(loginForm.password)
        }).then((data)=>{
            if(data){
                token.value = data.token
                userInfo.value = {  username: loginForm.username,remember:loginForm.remember,password: loginForm.password }
                router.replace("status")
                Message.success("登录成功")
            }
        })
    }

    const logout = () => {
        if(!userInfo.value.remember){
            userInfo.value = null
        }
        token.value = ""
        router.replace("login")
    }

    
    const isLogin = computed(() => token.value !== "")

    return {
        loginForm,
        login,
        logout,
        isLogin,
        userInfo
    }
}
